//
//  FocusMoreViewController.m
//  Everest
//
//  Created by Liu Chengbo on 14/12/25.
//  Copyright (c) 2014年 ThreeL. All rights reserved.
//

#import "FocusMoreViewController.h"
#import "FocusMoreCell.h"
#import "UIImageView+WebCache.h"
#import "NetHandler.h"
#import "FocusMore.h"
#import "MJRefresh.h"
#import "FoThreeViewController.h"
#import "FocusThree.h"
#import "UIColor+AddColor.h"
#import "JingRoundView.h"
#import "AvReadioPlayer.h"
#define kFocusPicHeight 175
#define kPage 1

@interface FocusMoreViewController () <UITableViewDataSource, UITableViewDelegate, JingRoundViewDelegate>
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) NSMutableArray *arr;
@property (nonatomic, retain) NSMutableDictionary *focusDic;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, retain) JingRoundView *roundView;

@end

@implementation FocusMoreViewController
- (void)dealloc
{
    [_roundView release];
    [_focusDic release];
    [_tableView release];
    [_arr release];
    [super dealloc];
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.arr = [NSMutableArray array];
        self.page = 1;
    }
    return self;
}
- (void)handleData
{
    [NetHandler getDataWithUrl:@"http://mobile.ximalaya.com/m/subject_list?device=iPhone&page=1&per_page=20" completion:^(NSData *data) {
        
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        NSMutableArray *tempArr = [result objectForKey:@"list"];
        
        self.focusDic = [NSMutableDictionary dictionary];
        for (NSDictionary *dic in tempArr) {
            
            FocusMore *focus = [[FocusMore alloc] initWithDictionary:dic];
            // 将NSNumber转为NSString
            NSString *tempstr = [focus.releasedAt description];
            // 截取前十位字符串
            NSString *istr = [tempstr substringToIndex:10];
            // 将字符串转为数字
            int uptime = [istr intValue];
            // 初始化date
            NSDate *date = [NSDate date];
            // 计算当前时间距1970年的秒数
            NSTimeInterval time = [date timeIntervalSince1970];
            // 计算日期
            NSDate *date1 = [NSDate dateWithTimeIntervalSinceNow:- (time - uptime)];
            // 将日期转为字符串
            NSString *day = [NSString stringWithFormat:@"%@", date1];
            // 截取前四位 作为 年
            NSString *year = [day substringToIndex:4];
            // 截取中间的两位 作为 月
            NSRange range = NSMakeRange(5, 2);
            NSString *month = [day substringWithRange:range];
            // 年 月 拼接
            NSString *my = [NSString stringWithFormat:@"%@.%@", year, month];
            // 取出focusDic字典中的所有key
            NSArray *allKey = [self.focusDic allKeys];
            // 如果 key的数组中包含 my 这个 key 就把所对应的对象 放到key 对应的数组中
            if ([allKey containsObject:my]) {
                [[self.focusDic objectForKey:my] addObject:focus];
                // 如果 没有 my 这个 key
            } else {
                // 新建一个装对象的数组
                NSMutableArray *focusArr = [NSMutableArray array];
                // 把对象放到数组中
                [focusArr addObject:focus];
                // 把数组 通过 key 存到字典中
                [self.focusDic setObject:focusArr forKey:my];
            }
            // 不要忘记内存管理
            [focus release];
        }
        
        // 数组降序排序
        // 如果数组不为空 就移除掉数组中所有的对象
        if (self.arr.count != 0) {
            [self.arr removeAllObjects];
        }
        // 取出了字典中的所有key 先升序排列
        NSArray *arr = [[self.focusDic allKeys] sortedArrayUsingSelector:@selector(compare:)];
        // 再 按照索引号从大到小访问数组的元素 reverseObjectEnumerator(需要记住的方法)
        for (NSString *str in [arr reverseObjectEnumerator]) {
            // 把排好序的 key 存到 数组中
            [self.arr addObject:str];
        }
        // 不要忘记刷新数据
        [self.tableView reloadData];
    }];
}
- (void)viewWillAppear:(BOOL)animated
{
    // 自定义tabbar
    UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height - 49, self.view.bounds.size.width, 49)];
    [self.view addSubview:backView];
    backView.backgroundColor = [UIColor tabBarColor];
    // 返回键
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [backView addSubview:backButton];
    backButton.frame = CGRectMake(10, 10, 30, 29);
    [backButton setImage:[UIImage imageNamed:@"iconfont-gerenfanhui.png"] forState:UIControlStateNormal];
    [backButton setTintColor:[UIColor sectionColor]];
    [backButton addTarget:self action:@selector(backButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    // 播放键
    self.roundView = [JingRoundView defaultJingRoundView];
    self.roundView.frame = CGRectMake((self.view.bounds.size.width / 2) - 30, - 10, 60, 60);
    self.roundView.delegate = self;
    self.roundView.rotationDuration = 4.0;
    [backView addSubview:self.roundView];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"今日焦点";
    self.navigationItem.hidesBackButton = YES;
    self.tabBarController.tabBar.hidden = YES;
    self.roundView.isPlay = NO;
    
    // 调用数据
    [self handleData];
    // 创建tableView
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    // 设置代理
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    // 添加到view上
    [self.view addSubview:self.tableView];
    // 设置颜色为透明
    self.tableView.backgroundColor = [UIColor clearColor];
    // 不要忘记内存管理
    [_tableView release];
    // 最后要调用刷新方法(仅用于需要刷新的页面)
    [self setupRefresh];
    
}
// 自定义tabbar中播放按钮方法
-(void)playStatuUpdate:(BOOL)playState
{
    NSLog(@"%@...", playState ? @"播放": @"暂停了");
    if (playState == YES) {
        NSLog(@"播放");
        AvReadioPlayer *avPlayer = [AvReadioPlayer defaultAvPlayer];
        [avPlayer play];
    } else {
        NSLog(@"暂停");
        AvReadioPlayer *avPlayer = [AvReadioPlayer defaultAvPlayer];
        [avPlayer pause];
        
    }
}
- (void)backButtonClicked:(UIButton *)button
{
    NSLog(@"返回上一页");
    [self.navigationController popViewControllerAnimated:YES];
}
// 区个数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [self.focusDic allKeys].count;
}
// 区高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}
// 区内容
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSString *str = [self.arr objectAtIndex:section];
    return str;
}
// cell颜色
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell.backgroundColor = [UIColor clearColor];
}
// cell个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // 通过 区名(key) 找到对应的value(数组) value的个数就是cell的个数
    NSMutableArray *arr = [self.focusDic objectForKey:[self.arr objectAtIndex:section]];
    return arr.count;
}
// cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kFocusPicHeight;
}
// 向cell中放内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *str = @"reuse";
    FocusMoreCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
    if (cell == nil) {
        cell = [[FocusMoreCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:str];
    }
    // 点击cell没有填充颜色
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    // cell赋值
    cell.foc = [[self.focusDic objectForKey:[self.arr objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
    return cell;
}
// 点击cell方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    FoThreeViewController *foThreeVC = [[FoThreeViewController alloc] init];
    // 给下一界面传值
    foThreeVC.focus = [[self.focusDic objectForKey:[self.arr objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
    // 推出到下一界面
    [self.navigationController pushViewController:foThreeVC animated:YES];
    // 内存管理
    [foThreeVC release];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 如何使用第三方刷新的类?
 处理刷新出来的数据 (和上边的数据处理差不多 区别有以下几点)
 1. 多了一个计算页数
 self.page = self.page + kPage;
 2. 少了下面这句话(在for循环之外的)
 self.focusDic = [NSMutableDictionary dictionary];
 3. 放到初始化中
 self.arr = [NSMutableArray array];
 要用刷新的第三方 (有以下几点)
 1. 引用第三方
 #import "MJRefresh.h"
 2. 复制以下方法
 3. 在viewDidLoad里调用
 [self setupRefresh];
*/

// 处理刷新出来的数据 (和上边的数据处理差不多 区别有以下几点)
- (void)handleFooterData
{
    self.page = self.page + kPage;
    NSString *str = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/subject_list?device=iPhone&page=%ld&per_page=20", self.page];
    [NetHandler getDataWithUrl:str completion:^(NSData *data) {
        
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        NSMutableArray *tempArr = [result objectForKey:@"list"];
        
//        self.focusDic = [NSMutableDictionary dictionary];
        for (NSDictionary *dic in tempArr) {
            
            FocusMore *focus = [[FocusMore alloc] initWithDictionary:dic];
            // 将NSNumber转为NSString
            NSString *tempstr = [focus.releasedAt description];
            // 截取前十位字符串
            NSString *istr = [tempstr substringToIndex:10];
            // 将字符串转为数字
            int uptime = [istr intValue];
            // 初始化date
            NSDate *date = [NSDate date];
            // 计算当前时间距1970年的秒数
            NSTimeInterval time = [date timeIntervalSince1970];
            // 计算日期
            NSDate *date1 = [NSDate dateWithTimeIntervalSinceNow:- (time - uptime)];
            // 将日期转为字符串
            NSString *day = [NSString stringWithFormat:@"%@", date1];
            // 截取前四位 作为 年
            NSString *year = [day substringToIndex:4];
            // 截取中间的两位 作为 月
            NSRange range = NSMakeRange(5, 2);
            NSString *month = [day substringWithRange:range];
            // 年 月 拼接
            NSString *my = [NSString stringWithFormat:@"%@.%@", year, month];
            
            NSArray *allKey = [self.focusDic allKeys];
            if ([allKey containsObject:my]) {
                [[self.focusDic objectForKey:my] addObject:focus];
            } else {
                NSMutableArray *focusArr = [NSMutableArray array];
                [focusArr addObject:focus];
                [self.focusDic setObject:focusArr forKey:my];
            }
            [focus release];
        }
        
        // 数组降序排序
        
        if (self.arr.count != 0) {
            [self.arr removeAllObjects];
        }
        NSArray *arr = [[self.focusDic allKeys] sortedArrayUsingSelector:@selector(compare:)];
        for (NSString *str in [arr reverseObjectEnumerator]) {
            [self.arr addObject:str];
        }
        [self.tableView reloadData];
    }];
}

- (void)setupRefresh
{
    //    NSLog(@"进入了setupRefresh");
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
//    进入刷新状态(一进入程序就下拉刷新)
    [self.tableView headerBeginRefreshing];
    
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
}



#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    
    //1. 在这调用请求网络数据方法（刷新数据）
    
    [self handleData];
    
    
    //2. 2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.tableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.tableView headerEndRefreshing];
    });
}

//   进入加载状态
- (void)footerRereshing
{
    //1. 拼接口等操作
    // 请求加载数据
    
    [self handleFooterData];
    
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.tableView reloadData];
        [self.tableView footerEndRefreshing];
    });
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
